//
//  MeVC.m
//  OC_Poj_demo
//
//  Created by weixin on 2018/7/20.
//  Copyright © 2018年 weixn. All rights reserved.
//

#import "MeVC.h"
#import "MeRegisterVC.h"
#import "MyHelpCentre.h"

#import "MeSignatureV.h"
#import "MeVCTbv.h"
#import "NoLoginView.h"
#import "MyQRCodeWebVC.h"
#import "LeftVC.h"


#import <UMPush/UMessage.h>
#import <UMCommon/UMCommon.h>

#import "UIViewController+CWLateralSlide.h"

@interface MeVC ()

@property (nonatomic,strong)NoLoginView *noLoginView;//未登录

@property (nonatomic,strong)MeVCTbv * Tbv;

@property (nonatomic,strong)BaseBtn * mineBtnMeun;

@property (nonatomic,strong)BaseBtn * helpBtn;

@property (nonatomic,strong)BaseBtn * SGQRCodeBtn;//二维码扫描 (活动)

@property (nonatomic,strong)UIImageView *moneyImageView;//二维码扫描 (图片)

@property (nonatomic,strong)BaseBtn * exiteBtn;//退出按钮

@property (nonatomic,strong)BaseBtn * POPBtn;//返回按钮

@property (nonatomic,strong)LeftVC * leftVC;//侧滑控制器




@end

@implementation MeVC

    
- (void)viewDidLoad {

    [self setNav];
    [self setUI];
    [self setRac];
    //添加侧滑
    [self addDrawer];
    
    if (@available(iOS 11.0, *)) {
        self.Tbv.contentInsetAdjustmentBehavior =   UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    

}

-(void)setRac{
    [RACObserve(kUSER_INFO_MANAGER, avatar) subscribeNext:^(id  _Nullable x) {
        NSString *path = [NSString stringWithFormat:@"http://mtime-1252014125.file.myqcloud.com%@",kUSER_INFO_MANAGER.avatar];
        self.Tbv.picUser = path;
        [self.Tbv reloadData];
        
    }];
    
    [RACObserve(kUSER_INFO_MANAGER, nickName) subscribeNext:^(id  _Nullable x) {
        self.Tbv.userName = kUSER_INFO_MANAGER.nickName;
        [self .Tbv reloadData];
    }];
    
    [RACObserve(kUSER_INFO_MANAGER, userId) subscribeNext:^(id  _Nullable x) {
        
        if (kUSER_INFO_MANAGER.userId.length==0) {
            self.Tbv.hidden = YES;
            self.exiteBtn.hidden = YES;
            //            self.mineBtnMeun.hidden = YES;
            self.noLoginView.hidden = NO;
            self.SGQRCodeBtn.hidden = YES;
            self.moneyImageView.hidden = YES;
            //            [self.isLoginView addSubview:self.imageIsLogin];
            //            [self.isLoginView addSubview:self.viewSigna];
            //            [self.isLoginView addSubview:self.labIsLogin];
            //            [self.isLoginView addSubview:self.btnLogin];
            //            self.viewSigna.frame = CGRectMake(0,CGRectGetMaxY(self.isLoginView.frame)-75-48,kScreenW,75+48);
        }else{
            self.exiteBtn.hidden = NO;
            self.noLoginView.hidden = YES;
            self.Tbv.hidden = NO;
            self.mineBtnMeun.hidden = NO;
            self.SGQRCodeBtn.hidden = NO;
        }
        if ([Main_Token_Model_MANAGER.isToken isEqualToString:@"1"]){
            self.SGQRCodeBtn.hidden = YES;
        }
    }];
}

-(void)setUI{


    
    [self.view addSubview:self.noLoginView];
    [self.view addSubview:self.SGQRCodeBtn];
    [self.view addSubview:self.moneyImageView];
    

    
    [self.mineBtnMeun mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kStatusBarHeight);
        make.left.equalTo(self.view).offset(10);
        make.height.width.mas_equalTo(40);
    }];
    
    [self.SGQRCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kStatusBarHeight);
        make.right.equalTo(self.view).offset(-10);
        make.height.width.mas_equalTo(40);
    }];
    
    [self.moneyImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(36, 20));
        make.top.equalTo(self.SGQRCodeBtn.mas_bottom).offset(3);
        make.right.equalTo(self.SGQRCodeBtn.mas_right).offset(-3);
    }];
    
    
    [self.Tbv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mineBtnMeun.mas_bottom).offset(0);
        make.left.right.equalTo(self.view).offset(0);
        if ([Main_Token_Model_MANAGER.isToken isEqualToString:@"1"]){
            make.bottom.equalTo(self.view).offset(-kBottomSafeHeight);
        }else{
            make.bottom.equalTo(self.view).offset(0);
        }
    }];
    
    [self.view bringSubviewToFront:self.moneyImageView];
    
    if ([Main_Token_Model_MANAGER.isToken isEqualToString:@"1"]){
        
        [self.POPBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(kStatusBarHeight);
            make.left.equalTo(self.view).offset(10);
            make.height.width.mas_equalTo(40);
        }];
        [self.exiteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(kStatusBarHeight);
            make.right.equalTo(self.view).offset(-10);
            make.height.width.mas_equalTo(40);
        }];
    }else{
        [self.exiteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(kStatusBarHeight);
            make.left.equalTo(self.view).offset(10);
            make.height.width.mas_equalTo(40);
        }];
    }

}

-(MeVCTbv *)Tbv{
    if (!_Tbv) {
        _Tbv = [[MeVCTbv alloc]initializeFrame:CGRectMake(0, 0, 1, 1) isMj:0 isEstimatedRowHeight:YES addRegisterNib:@[@"MainBizQutoeCellText",@"MainHeadCell",@"MainFootCell",@"MeBizQutoeCell",@"MyviewSignaCell",@"MeVCTbvTypeCell",@"TaskMeVCCell",@"Me_MainBtn_Cell_WX"]];
        [self.view addSubview:_Tbv];
    }
    return _Tbv;
}

-(BaseBtn *)exiteBtn{
    if (!_exiteBtn) {
        _exiteBtn = [[BaseBtn alloc]initializeFrame:CGRectMake(0, 0, 1, 1) NormalText:nil NormalTextColor:nil SeleText:nil NormalImage:@"我的_退出登录" SeleImage:nil SeleTextColor:nil font:nil isBold:nil];
        _exiteBtn.backgroundColor = [UIColor clearColor];
        
        
        if ([Main_Token_Model_MANAGER.isToken isEqualToString:@"1"]){
            UIImage *image = [UIImage imageNamed:@"我的_退出登录"];
            image =[image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
            
            [_exiteBtn setImage:image forState:UIControlStateNormal];
            [_exiteBtn.imageView setTintColor:[UIColor whiteColor]];
        }

            @weakify(self);
            [[_exiteBtn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
                @strongify(self);
                [self setUP];
            }];
            [self.view addSubview:_exiteBtn];
            
        }
    return _exiteBtn;
}



-(void)setUP{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"退出登录" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    }];
    
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self setUPLog];
    }];
    // Add the actions.
    
    [alertController addAction:cancelAction];
    
    [alertController addAction:otherAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

-(void)setUPLog{
    [self.mineBtnMeun mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kStatusBarHeight);
        make.left.equalTo(self.view).offset(10);
        make.height.width.mas_equalTo(40);
    }];
    //移除别名
    [UMessage removeAlias:kUSER_INFO_MANAGER.userId type:@"userId" response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        NSLog(@"");
    }];
    [kUSER_INFO_MANAGER saveCookie];
    
    kUSER_INFO_MANAGER.userId = @"";
    [kUSER_INFO_MANAGER removeUserInfo];
    [kUSER_INFO_MANAGER cleanCookie];
    kUSER_INFO_MANAGER.getMyEnquiryList = NO;
    kUSER_INFO_MANAGER.getFollowGoods = NO;
    [self dismissViewControllerAnimated:YES completion:nil];
    

}

-(BaseBtn *)mineBtnMeun{
    if (!_mineBtnMeun) {
        _mineBtnMeun = [[BaseBtn alloc]initializeFrame:CGRectMake(0, 0, 1, 1) NormalText:nil NormalTextColor:nil SeleText:nil NormalImage:@"我的_帮助" SeleImage:nil SeleTextColor:nil font:nil isBold:nil];
        _mineBtnMeun.backgroundColor = [UIColor clearColor];
        if ([Main_Token_Model_MANAGER.isToken isEqualToString:@"1"]){
            UIImage *image = [UIImage imageNamed:@"我的_帮助"];
            image =[image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
            
            [_mineBtnMeun setImage:image forState:UIControlStateNormal];
            [_mineBtnMeun.imageView setTintColor:[UIColor whiteColor]];
        }
        

        
        @weakify(self);
        [[_mineBtnMeun rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
//            if (kUSER_INFO_MANAGER.userIsLogin) {
////                [self defaultAnimationFromLeft];
//            }else{
                MyHelpCentre *vc = [[MyHelpCentre alloc]init];
                [self.navigationController pushViewController:vc animated:YES];
//            }
        }];
        [self.view addSubview:_mineBtnMeun];
        
        
//        BaseBtn * btn = [[BaseBtn alloc]initializeFrame:CGRectMake(0, 0, 1, 1) NormalText:nil NormalTextColor:nil SeleText:nil NormalImage:@"我的_帮助" SeleImage:nil SeleTextColor:nil font:nil isBold:nil];
//        [_mineBtnMeun addSubview:btn];
//        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(self.view).offset(kStatusBarHeight);
//            make.left.equalTo(self.view).offset(14);
//            make.height.width.mas_equalTo(40);
//        }];
//        btn.enabled = NO;

    }
    return _mineBtnMeun;
}



-(void)upUserInfo{
    @weakify(self);
    //更新用户信息
    [[AccountService getUserInfo]subscribeNext:^(ResponseData * x) {
        @strongify(self);
        if (x.success) {
            kUSER_INFO_MANAGER.avatar = x.responseRawData[@"data"][@"avatar"];
            kUSER_INFO_MANAGER.nickName = x.responseRawData[@"data"][@"nickName"];
            kUSER_INFO_MANAGER.phone = x.responseRawData[@"data"][@"phone"];
            NSString * newMsgCount = x.responseRawData[@"data"][@"newMsgCount"];
            self.Tbv.NewMsgCont = [newMsgCount integerValue];
            
//            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
//            NSString *Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];  //获取
        
        }else{
            //
        }
    }];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if (kUSER_INFO_MANAGER.userIsLogin) {
        [self upUserInfo];
    }

    if (!kUSER_INFO_MANAGER.userIsLogin) {
        self.noLoginView.hidden = NO;
//        [self.mineBtnMeun setImage:[UIImage imageNamed:@"我的_帮助"] forState:UIControlStateNormal];
        [self.mineBtnMeun mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(kStatusBarHeight);
            make.left.equalTo(self.view).offset(10);
            make.height.width.mas_equalTo(40);
        }];
    }else{
        [self.mineBtnMeun mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(kStatusBarHeight);
            make.left.equalTo(self.view).offset(45);
            make.height.width.mas_equalTo(40);
        }];
        self.noLoginView.hidden = YES;
//        [self.mineBtnMeun setImage:[UIImage imageNamed:@"mine_btn_meun"] forState:UIControlStateNormal];
        [self.Tbv loadData];
    }
    
    
    /** 处理发布页面tabbar显示问题 */
//    if ([DEFAULReleaseV iseqHidden]) {
//        [self.tabBarController.tabBar setHidden:NO];
//    }else{
//        [self.tabBarController.tabBar setHidden:YES];
//    }
    
    if (kUSER_isPublishImage.type == YES && !kUSER_isPublishImage.typeClose) {
        kUSER_isPublishImage.hidden = NO;
    }
}




-(void)setNav{
    /** 还是会出现手动侧滑返回会有系统导航栏遮盖的情况 需要注意下 */
    [self.baseNavigationView setHiddenNav:YES VC:self];

    [self setNavigationTitle:@""];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
    [self.baseNavigationView setBackgroundColor:[UIColor clearColor]];
    self.baseNavigationView.bottomLineView.backgroundColor = [UIColor clearColor];
    self.baseNavigationView.isShowShadow = YES;
//    登录或注册
    self.baseNavigationView.leftButton1.hidden = YES;
    [self.baseNavigationView setBackgroundColor:[UIColor clearColor]];
    self.baseNavigationView.bottomLineView.backgroundColor = [UIColor clearColor];
    /* TODO: ================= 导航栏箭头颜色 =================*/
    @weakify(self);
    [self.baseNavigationView setNavigationViewClickBlock:^(NavigationViewClickType clickType, UIButton *button) {
        @strongify(self);
        switch (clickType) {
            case NavigationViewClickTypeLeft1:{
                for (UIViewController *controller in self.navigationController.viewControllers) {
                    if ([controller isKindOfClass:[UIViewController class]]) {
                        UIViewController *A =(UIViewController *)controller;
                        [self.navigationController popToViewController:A animated:YES];
                    }
                }
            }break;
                
            default:
                break;
        }
    }];
    
    


}







- (NoLoginView *)noLoginView{
    if (!_noLoginView) {
        _noLoginView = [[NoLoginView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
    }
    return _noLoginView;
}


-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    if (kUSER_isPublishImage.type == YES && !kUSER_isPublishImage.typeClose) {
        kUSER_isPublishImage.hidden = YES;
    }
}

- (UIImageView *)moneyImageView {
    
    if (!_moneyImageView) {
        
        _moneyImageView = [UIImageView new];
        
        if ([Main_Token_Model_MANAGER.isToken isEqualToString:@"0"]) {
//        _moneyImageView.image = [UIImage imageNamed:@"我的_送现金"];
        }
        
    }
    return _moneyImageView;
}

- (BaseBtn *)SGQRCodeBtn{
    if (!_SGQRCodeBtn) {
        _SGQRCodeBtn = [[BaseBtn alloc]initializeFrame:CGRectMake(0, 0, 0, 0) NormalImage:@"我的_打卡" SeleImage:@""];
        _SGQRCodeBtn.backgroundColor = [UIColor clearColor];


        if ([Main_Token_Model_MANAGER.isToken isEqualToString:@"1"]){
            UIImage *image = [UIImage imageNamed:@"我的_打卡"];
            image =[image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
            
            [_SGQRCodeBtn setImage:image forState:UIControlStateNormal];
            [_SGQRCodeBtn.imageView setTintColor:[UIColor whiteColor]];

        }
        
        @weakify(self);
        [[_SGQRCodeBtn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            MyQRCodeWebVC * vc = [[MyQRCodeWebVC alloc]init];
            vc.navStyle = 1;
            [self.navigationController pushViewController:vc animated:YES];
            vc.url = [NSString stringWithFormat:@"%@/#/activity/merchant",RootUrlWeb];

        }];
    }
    return _SGQRCodeBtn;
}


-(BaseBtn *)POPBtn{
    if (!_POPBtn) {
        _POPBtn = [BaseBtn initCustomBtn:@[@""]];
        _POPBtn.backgroundColor = [UIColor clearColor];
        UIImage *image = [UIImage imageNamed:@"common_back"];
        image =[image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        [_POPBtn setImage:image forState:UIControlStateNormal];
        [_POPBtn setTintColor:[UIColor whiteColor]];
        _POPBtn.hidden = YES;
        [self.view addSubview:_POPBtn];

        [[_POPBtn addTag]subscribeNext:^(id  _Nullable x) {
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }
    return _POPBtn;
}












#pragma 侧边栏模块
- (void)addDrawer{
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self setupNavBarItem];
    // 注册手势驱动
    __weak typeof(self)weakSelf = self;
    
    [self cw_registerShowIntractiveWithEdgeGesture:NO transitionDirectionAutoBlock:^(CWDrawerTransitionDirection direction) {
        if (direction == CWDrawerTransitionFromLeft) { // 左侧滑出
            if (kUSER_INFO_MANAGER.userIsLogin) {
                [weakSelf defaultAnimationFromLeft];
            }
        } else if (direction == CWDrawerTransitionFromRight) { // 右侧滑出
            
        }
    }];
    
}

- (void)setupNavBarItem {
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:self action:@selector(defaultAnimationFromLeft)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:self action:@selector(scaleYAnimationFromRight)];
}


// 左侧划出
- (void)defaultAnimationFromLeft {
    [self cw_showDefaultDrawerViewController:self.leftVC];
    
    //    [self cw_showDrawerViewController:self.leftVC animationType:CWDrawerAnimationTypeMask configuration:nil];
    
}



#pragma mark - 自定义处理手势冲突接口
#if 0
- (BOOL)cw_gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;// 可以在这里实现自己需要处理的手势冲突逻辑
}
#endif

- (LeftVC *)leftVC {
    if (_leftVC == nil) {
        _leftVC = [LeftVC new];
    }
    return _leftVC;
}
@end
